package com.epfresh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.epfresh.R;
import com.epfresh.activity.CommonStoreActivity;
import com.epfresh.activity.SearchStoreActivityNew;
import com.epfresh.adapter.SearchStoreViewBinder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.ListStore;
import com.epfresh.global.BaseFragment;
import com.epfresh.views.MultiStateView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
import multitype.MultiTypeAdapter;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

public class SearchStoreFragment extends BaseFragment {
    private PtrFrameLayout ptrFrameLayout;
    private MultiStateView msv_view;
    private RecyclerView rv_store_list;

    private MultiTypeAdapter multiAdapter;
    private List<Object> items = new ArrayList<>();
    private LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();

    private String keyWords;
    private String marketId;
    private int pageNum = 0;
    private boolean isFirstLoad = true;
    private boolean isRefresh = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_search_store_new, container, false);
        initView(view);
        return view;
    }

    @Override
    public String getBaseTag() {
        return "SearchStoreFragment";
    }

    public void setData(String keyWords,String marketId) {
        this.keyWords=keyWords;
        this.marketId=marketId;
    }

    private void initView(View view) {
        ptrFrameLayout = view.findViewById(R.id.ptr_frame_layout);
        msv_view = view.findViewById(R.id.msv_view);
        rv_store_list = view.findViewById(R.id.rv_store_list);

        msv_view.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        msv_view.setViewForState(R.layout.empty_view_no_store, MultiStateView.VIEW_STATE_EMPTY);
        msv_view.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_ERROR);

        multiAdapter = new MultiTypeAdapter();
        ptrFrameLayout.setPtrHandler(ptrHandler);

        SearchStoreViewBinder searchStoreViewBinder = new SearchStoreViewBinder();
        searchStoreViewBinder.setOnStoreClickListener(new SearchStoreViewBinder.OnStoreClickListener() {
            @Override
            public void onStoreClick(ListStore item) {
                Intent storeIntent = new Intent(getContext(), CommonStoreActivity.class);
                storeIntent.putExtra("storeId",item.getId());
                startActivity(storeIntent);
            }
        });
        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreDelegate.attach(rv_store_list, loadMoreSubject);

        multiAdapter.register(ListStore.class,searchStoreViewBinder);
        multiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        multiAdapter.setItems(items);

        rv_store_list.setLayoutManager(new LinearLayoutManager(getContext()));
        rv_store_list.setAdapter(multiAdapter);
        refresh();
    }

    /**
     * 刷新
     */
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv_store_list, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    /**
     * 加载更多
     */
    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();
            loadMore();
        }
    };

    private void refresh() {
        items.clear();
        pageNum = 0;
        isRefresh = true;
        reqStoreSearchResult();
    }

    private void loadMore() {
        pageNum += 1;
        isRefresh = false;
        reqStoreSearchResult();
    }

    private void reqStoreSearchResult() {
        RequestEntityMap requestEntityMap = new RequestEntityMap();
        requestEntityMap.setCmd(AppPurchaseRouterConstant.cmd_store_store_list);
        requestEntityMap.putParameter("sortDirection", "DESC");
        requestEntityMap.putParameter("name", keyWords);
        requestEntityMap.putParameter("pageNumber", pageNum);
        requestEntityMap.putParameter("pageSize", 10);
        requestEntityMap.putParameter("sortProperty", "name");
        if (marketId != null) {
            String[] strings = new String[1];
            strings[0] = marketId;
            requestEntityMap.putParameter("marketIds", strings);
        }

        request(requestEntityMap, AppPurchaseRouterConstant.cmd_store_store_list, new OnRequestListener<ContentEntity<ListStore>>() {
            @Override
            public ContentEntity<ListStore> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<ListStore>>() {
                }.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                ptrFrameLayout.refreshComplete();
                msv_view.setViewState(MultiStateView.VIEW_STATE_ERROR);
                T.toast(failCode + "");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                ptrFrameLayout.refreshComplete();
                msv_view.setViewState(MultiStateView.VIEW_STATE_ERROR);
                T.toast(failCode + "");
            }

            @Override
            public void onStart(Object tag) {
                if (isFirstLoad) {
                    msv_view.setViewState(MultiStateView.VIEW_STATE_LOADING);
                    isFirstLoad = false;
                }
            }

            @Override
            public void onResponse(ResponseEntity<ContentEntity<ListStore>> response, Object tag) {
                ptrFrameLayout.refreshComplete();
                msv_view.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                if (response.getResponseElement() != null) {
                    List<ListStore> content = response.getResponseElement().getContent();
                    if (content != null) {
                        if (content.size() > 0) {
                            loadMoreDelegate.addAllItem(items, content);
                            if (content.size() < 10) {
                                loadMoreDelegate.setStatusNoMore();
                            } else {//等于10
                                loadMoreDelegate.setStatusNormal();
                            }
                        } else {
                            if (isRefresh) {
                                msv_view.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            }
                            loadMoreDelegate.setStatusNoMore();
                        }
                    }
                }
                multiAdapter.notifyDataSetChanged();
            }
        });
    }
}
